<template>
  <div class="admin-container">
    <h1>物流合作商管理</h1>

    <!-- 查询和新增按钮放在同一行 -->
    <div class="top-bar">
      <div class="search-container">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索合作商名称..."
          class="search-input"
        />      
        <button @click="searchPage">查询</button>
        
        <el-checkbox 
          v-model="filterDefault"
          style="margin-left: 15px;"
        >
          仅显示默认合作商
        </el-checkbox>
      </div>

      <button class="add-button" @click="openAddModal">新增合作商</button>
    </div>

    <!-- 合作商列表：添加overflow-x确保小屏幕可横向滚动 -->
    <div class="table-container">
      <table>
        <thead>
          <tr>
            <th width="18%">合作商名称</th>
            <th width="16%">合作开始日期</th>
            <th width="16%">合作结束日期</th>
            <th width="10%">是否默认</th>
            <th width="18%">创建时间</th>
            <th width="16%">操作</th> <!-- 大幅增加操作列宽度，确保3个按钮能放下 -->
          </tr>
        </thead>
        <tbody>
          <tr v-for="partner in partners" :key="partner.partnerId">
            <td>{{ partner.partnerName }}</td>
            <td>{{ formatDate(partner.cooperationStartDate) }}</td>
            <td>{{ formatDateOrInfinite(partner.cooperationEndDate) }}</td>
            <td>
              <span :class="['status-tag', partner.isDefault ? 'default' : 'not-default']">
                {{ partner.isDefault ? '是' : '否' }}
              </span>
            </td>
            <td>{{ formatDateTime(partner.createTime) }}</td>
            <!-- 操作列：用flex布局确保按钮横向排列且不溢出 -->
            <td class="operation-cell">
              <button 
                @click="setAsDefault(partner.partnerId)" 
                :disabled="partner.isDefault"
                class="operate-btn default-button"
              >
                设为默认
              </button>
              <button @click="openEditModal(partner)" class="operate-btn edit-button">编辑</button>
              <button @click="confirmDelete(partner)" class="operate-btn delete-button">删除</button>
            </td>
          </tr>
          <!-- 空数据提示 -->
          <tr v-if="params.recordCount === 0">
            <td colspan="7" class="empty-cell">暂无合作商数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页功能：调整间距，避免与表格重叠 -->
    <div class="pagination-container">
      <el-pagination
        :page-size="params.pageSize"
        :total="params.recordCount"
        v-model:current-page="params.pageNum"
        @current-change="handleCurrentChange"
        @prev-click="prevPage" 
        @next-click="nextPage"
        layout="total,prev,pager,next"
      />
    </div>

    <!-- 新增/编辑合作商弹窗 -->
    <el-dialog 
      :title="isEditing ? '编辑合作商' : '新增合作商'" 
      v-model="showModal" 
      width="600px" 
      :center="true" 
      :close-on-click-modal="false" 
      :before-close="closeModal"
    >
      <el-form-item label="合作商名称" :rules="[{ required: true, message: '请输入合作商名称', trigger: 'blur' }]">
        <el-input v-model="formData.partnerName" placeholder="请输入合作商名称"></el-input>
      </el-form-item>

      <div style="display: flex; gap: 10px;">
        <el-form-item label="合作开始日期" :rules="[{ required: true, message: '请选择合作开始日期', trigger: 'change' }]">
          <el-date-picker
            v-model="formData.cooperationStartDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="合作结束日期">
          <el-date-picker
            v-model="formData.cooperationEndDate"
            type="date"
            placeholder="选择结束日期（可选）"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </div>


      <span class="dialog-footer">
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="savePartner">保存</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog 
      title="确认删除"
      v-model="showDeleteConfirm" 
      width="400px" 
      :center="true"
    >
      <div style="text-align: center;">
        <p style="margin-bottom: 15px;">您确定要删除合作商 <span style="font-weight: bold;">{{ deletePartnerName }}</span> 吗？</p>
        <p style="color: #F56C6C;">此操作不可撤销</p>
      </div>
      
      <span class="dialog-footer">
        <el-button @click="showDeleteConfirm = false">取消</el-button>
        <el-button type="danger" @click="deletePartner">确认删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import {queryPage,insertSave,updateById,deleteById,updateDefault} from "@/api/partner";
//企业数据
const partners = ref([
]);

// 分页相关
const params = ref({
  pageNum: 1,
  pageSize: 5,
  recordCount: 0,
  pageCount: 0
});

// 搜索和筛选
const searchQuery = ref('');


// 表单相关
const showModal = ref(false);
const isEditing = ref(false);
const formData = ref({
  partnerId: null,
  partnerName: '',
  cooperationStartDate: '',
  cooperationEndDate: '',
  isDefault: 0,
  isDelete:0
});
const isDefaultBool=ref(0);
//查询函数
function searchPage(){

  queryPage(searchQuery.value,params.value.pageNum,params.value.pageSize)
    .then(response => {
      console.log(response);
      partners.value = response.list;
      params.value = response.pager;
    })
    .catch(error => {
      console.error('初始化查询失败:', error);
    });
}
// 页面挂载后执行初始化查询
onMounted(() => {
  // 这里调用queryPage，和组件初始化时执行的效果类似，但时机是在DOM挂载后
    searchPage();
});
// 删除确认相关
const showDeleteConfirm = ref(false);



// 格式化日期
const formatDate = (cellValue) => {
  if (!cellValue) return '-';
  const date = new Date(cellValue);
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
};

// 格式化日期或显示无限期
const formatDateOrInfinite = (cellValue) => {
  if (!cellValue) return '无限期';
  return formatDate(cellValue);
};

// 格式化日期时间
const formatDateTime = (cellValue) => {
  if (!cellValue) return '-';
  const date = new Date(cellValue);
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 分页事件处理
const handleCurrentChange = (val) => {
  params.value.pageNum = val;
  searchPage()
};
const currentPage = ref(1);
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    params.value.pageNum = currentPage.value;
    searchPage();
  }
};

const nextPage = () => {
  if (currentPage.value <params.value.pageCount ) {
    currentPage.value++;
    params.value.pageNum = currentPage.value;
    searchPage();
  }
};

// 打开新增模态框
const openAddModal = () => {
  isEditing.value = false;
  // 重置表单
  Object.assign(formData, {
    partnerId: null,
    partnerName: '',
    cooperationStartDate: new Date().toISOString().split('T')[0],
    cooperationEndDate: '',
    isDefault: 0,
  });
  showModal.value = true;
};

// 打开编辑模态框
const openEditModal = (partner) => {
  isEditing.value = true;
  // 填充表单数据
  Object.assign(formData.value, {...partner});
  showModal.value = true;
  
};

// 关闭模态框
const closeModal = () => {
    isDefaultBool.value=0
    formData.value={}
  showModal.value = false;
};

// 保存合作商
const savePartner = () => {
    formData.value.isDefault=isDefaultBool.value
  // 简单的表单验证
  if (!formData.value.partnerName) {
    ElMessage.error('请输入合作商名称');
    return;
  }
  
  if (!formData.value.cooperationStartDate) {
    ElMessage.error('请选择合作开始日期');
    return;
  }

  if (isEditing.value) {

    // 更新现有合作商
    updateById(formData.value)
    .then(response=>{
        console.log(response);
        ElMessage({
        message: '更新成功',
        type: 'success',
        duration: 2000 // 提示信息显示2秒后自动消失
      });
        searchPage()
    }).catch(error=>{
        console.error('更新失败:', error);
      // 显示失败提示
      ElMessage({
        message: '更新失败，请稍后重试',
        type: 'error',
        duration: 2000
      });
    })
  } else {
    // 添加新合作商
    insertSave(formData.value)
    .then(response=>{
        console.log(response);
        ElMessage({
        message: '新增成功',
        type: 'success',
        duration: 2000 // 提示信息显示2秒后自动消失
      });
        // 重置到第一页，确保能看到新添加或修改的数据
           currentPage.value = 1;
 searchPage()
    }).catch(error=>{
        console.error('添加失败:', error);
      // 显示失败提示
      ElMessage({
        message: '添加失败，请稍后重试',
        type: 'error',
        duration: 2000
      });
    })
  }
  
  closeModal();
};

// 确认删除
const confirmDelete = (partner) => {
    Object.assign(formData.value, {...partner});
  showDeleteConfirm.value = true;
};

// 执行删除
const deletePartner = () => {
    deleteById(formData.value.partnerId)
    .then(response=>{
        ElMessage({
        message: '删除成功',
        type: 'success',
        duration: 2000 // 提示信息显示2秒后自动消失
      });
        showDeleteConfirm.value = false;
        searchPage()
    }).catch(error=>{
        ElMessage({
        message: '删除失败，请稍后重试',
        type: 'error',
        duration: 2000
      });
    })
};

// 设置为默认
const setAsDefault = (partnerId) => {
    console.log(partnerId)
    updateDefault(partnerId)
    .then(response=>{
        console.log(response);
        ElMessage({
        message: '更换默认成功',
        type: 'success',
        duration: 2000 // 提示信息显示2秒后自动消失
      });
        searchPage()
    }).catch(error=>{
        console.error('更换失败:', error);
      // 显示失败提示
      ElMessage({
        message: '更换失败，请稍后重试',
        type: 'error',
        duration: 2000
      });
    })
};
</script>

<style scoped>
/* 容器样式：确保页面不溢出 */
.admin-container {
  width: 95%;
  max-width: 1600px; /* 限制最大宽度，避免大屏幕拉伸 */
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  font-family: 'Arial', sans-serif;
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-size: 28px;
  margin-bottom: 20px;
  color: #333;
}

/* 顶部栏样式 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap; /* 小屏幕自动换行 */
  gap: 15px;
}

.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-input {
  padding: 10px;
  width: 250px;
  border-radius: 4px;
  border: 1px solid #ccc;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.search-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
  outline: none;
}

.add-button {
  background-color: #007bff;
  color: white;
  padding: 12px 18px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.add-button:hover {
  background-color: #0056b3;
}


.table-container {
width: 100%;
overflow-x: auto; 
margin-top: 10px;
}


table {
width: 100%;
min-width: 1000px; 
margin-top: 10px;
border-collapse: collapse;
table-layout: fixed; 
word-break: break-all;
}

table, th, td {
border: 1px solid #ccc;
box-sizing: border-box;
}

/* 表头样式：优化列宽分配，优先保证操作列空间 */
th {
padding: 12px 8px;
text-align: center;
background-color: #f5f5f5;
font-weight: 500;
color: #333;
}


td {
padding: 12px 8px;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
box-sizing: border-box;
}


.operation-cell {
white-space: normal;
overflow: visible; 
text-overflow: clip;
display: flex; 
justify-content: center; 
align-items: center;
gap: 6px; 
}


.operate-btn {
padding: 6px 10px; 
border: none;
cursor: pointer;
border-radius: 4px;
font-size: 12px; 
transition: background-color 0.3s ease;
white-space: nowrap;
}


.default-button {
background-color: #67c23a;
color: white;
}

.default-button:hover:not(:disabled) {
background-color: #5daf34;
}

.default-button:disabled {
background-color: #b3e19d;
cursor: not-allowed;
color: #fff;
}

.edit-button {
background-color: #e6a23c;
color: white;
}

.edit-button:hover {
background-color: #cf9236;
}

.delete-button {
background-color: #dc3545;
color: white;
}

.delete-button:hover {
background-color: #c82333;
}

/* 状态标签样式：优化尺寸，避免挤压单元格 */
.status-tag {
padding: 3px 8px;
border-radius: 4px;
font-size: 12px;
display: inline-block;
}

.status-tag.default {
background-color: #f0f9eb;
color: #67c23a;
border: 1px solid #e1f3d8;
}

.status-tag.not-default {
background-color: #f4f4f5;
color: #909399;
border: 1px solid #e9e9eb;
}


.pagination-container {
margin-top: 20px;
text-align: right; 
padding-right: 10px;
}

/* 空数据提示：优化样式，确保居中显示 */
.empty-cell {
height: 100px;
line-height: 100px;
color: #909399;
font-size: 14px;
}

/* 弹窗按钮区域：优化间距 */
.dialog-footer {
display: flex;
justify-content: flex-end;
padding: 10px 0;
gap: 10px;
}

/* 表单项：优化间距，避免拥挤 */
.el-form-item {
margin-bottom: 20px;
}


@media (max-width: 768px) {
.operation-cell {
gap: 4px; 
}
.operate-btn {
padding: 4px 8px; 
font-size: 11px; 
}

.search-input {
width: 200px; /* 缩小搜索框宽度，避免顶部栏换行 */
}

th, td {
padding: 10px 4px; /* 缩小单元格内边距 */
}
}
</style>